/*
 *  @author zhangqiang
 *  @data 2017/07/26
 *   添加通行证
 * */

import React, { Component } from 'react';
import {Toast, DatePicker, List, Picker,Popup,Modal} from 'antd-mobile';
import { createForm } from 'rc-form';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { Title } from '../../components/common'
import BackMeanSure from '../../utils/backMeanSure';
import ReModal from '../../components/common/reModal'
import style from './index.scss'
import {connect} from 'react-redux';
import {
	setAddPass,
	deletePass,
	queryPass
} from '../../actions/addPassCheckActions'
import {InputItem} from '../../components/home'
import {FooterAlert} from '../../components/addPass'
import district from '../../components/addPass/provinceData/district';    //省份数据源
import common from '../../utils/common'
import '../../../styles/addPass.scss';
const passMaxDate = moment('2030-02-01 +0800', 'YYYY-MM-DD Z').utcOffset(8);
const passMinDate = moment('1900-02-01 +0800', 'YYYY-MM-DD Z').utcOffset(8);

let date = new Date();
let year = date.getFullYear();
let month = date.getMonth()+1;
let day = date.getDate();
const birthMaxDate = moment(`${year+'-'+month+'-'+day} +0800`, 'YYYY-MM-DD Z').utcOffset(8);
const birthMinDate = moment('1900-02-01 +0800', 'YYYY-MM-DD Z').utcOffset(8);
const alert = Modal.alert;

let checkInformation = {
	name: /^[\u4e00-\u9fa5]{1,12}$/
}
class AddPass extends Component {
    constructor(props) {
        super(props);
        this.state = {
	        surname: '',  //姓氏
	        surnameImg: false,
	        surnameWidth: '.3rem', // 姓氏的默认宽度
	        surnameNoBlur: true, //点击删除按钮不执行失去焦点验证
	        name: '', //姓名 自由类型
	        nameImg: false,
	        nameWidth: '.3rem', // 姓名的默认宽度
	        nameNoBlur: true, //点击删除按钮不执行失去焦点验证
	        pass: '', //通行证 自由类型
	        passImg: false,
	        passWidth: '.3rem', // 通行证的默认宽度
	        passNoBlur: true, //点击删除按钮不执行失去焦点验证
	        birthData:'', //出生日期
	        passData: '', //通行证日期
	        data: [],
	        cols: 1,
	        asyncValue: [],
	        pickerValue:'', //签发地
	        issueProvinceName: '', //签发名
	        issueProvinceId: '', //签发ID
	        issueOffice: '', //签发ID
	        sixName:'请选择性别', //性别
	        sixCheck: '',  //性别类行
	        disabled: false,
	        birthday: '',  //出生日期
	        validateEnd: '', //有效期日期
	        msg:''
        };
		this.showListPop = this.showListPop.bind(this);
		this.queryPass = this.queryPass.bind(this);
	    this.id = this.props.params.id;
	    this.type = this.props.params.type;
	    this.backMeanSureInstance = new BackMeanSure(this.showMeansureBox, 'addpass');
    }

    componentDidMount() {
	    switch (this.type){
		    case 'disabled':
			    common.setViewTitle('编辑港澳通行证');
			    this.queryPass();
		      this.setState({
			      surnameImg: 'correct',  //姓氏显示正确icon
			      surnameWidth: '.4rem',
			      nameImg:  'correct', // 名显示正确icon
			      nameWidth: '.4rem',
		      })

			    document.querySelector('#pass').style.color='#ababab';
			    document.querySelector('#surname').style.color='#ababab';
			    document.querySelector('#name').style.color='#ababab';
		    	break;
		    default:
			    common.setViewTitle('添加港澳通行证');
		    	break;
	    }
    }

    componentWillUnmount() {
	    Popup.hide(); //防止用户点击弹框，点击返回弹框没有消失的bug
	    sessionStorage.setItem('getRegionType',1)
    }

    //查询港澳证件
	queryPass(){
		let postData={
			id: this.id
		}
		let fmt = 'yyyy-MM-dd';
		queryPass(postData,(res)=>{
			this.setState({
				surname: res.passNameM,
				name: res.passNameX,
				pass: res.passCode,
				sixName: res.sex,
				issueProvinceName: res.issueProvinceName,
				issueProvinceId: res.issueProvinceId,
				issueOffice: res.issueOffice,
				birthday:common.format(res.birthday,fmt),
				validateEnd: common.format(res.validateEnd,fmt),
			})
			document.querySelectorAll('.am-list-extra')[0].style.color='#6a6a6a'; //出生日期
			document.querySelectorAll('.am-list-extra')[1].innerHTML=common.format(res.birthday,fmt);

			document.querySelectorAll('.am-list-extra')[1].style.color='#6a6a6a'; //有效日期
			document.querySelectorAll('.am-list-extra')[2].style.color='#6a6a6a'; //性别

			document.querySelectorAll('.am-list-extra')[3].style.color='#6a6a6a'; //签发地
			document.querySelectorAll('.am-list-extra')[3].innerHTML= res.issueProvinceName; //签发地
			document.querySelectorAll('.am-list-extra')[2].innerHTML=common.format(res.validateEnd,fmt);

		})
	}
	//弹出确认页
	showListPop() {
		let props = {
			choose: (check,name) => {
				console.log(check,name)
					this.setState({
						sixName: check,
						sixCheck: name
					});
					sessionStorage.setItem('visaType',check);
				document.querySelectorAll('.am-list-extra')[0].style.color='#6a6a6a';
				Popup.hide(); //隐藏
			}
		};

		Popup.show(<FooterAlert {...props}/>, {animationType: 'slide-up'});
	}
	/*
	* 提交保存
	* */
	addPassSubMit(){
		let state = this.state;
		if(state.pass==''){
			Toast.info('请输入正确的通行证号',1);
			return;
		}else if(state.surname==''){
			Toast.info('姓氏不能为空',1);
			return;
		}else if(!checkInformation.name.test(state.surname)){
		Toast.info('请输入正确的姓氏',1);
			return;
		}else if(state.name==''){
			Toast.info('名字不能为空',1);
			return;
		}else if(!checkInformation.name.test(state.name)){
			Toast.info('请输入正确的名字',1);
			return;
		}else if(state.sixName=='请选择性别'){
			Toast.info('性别不能为空',1);
			return;
		}else if(!state.birthday){
			Toast.info('出生日期不能为空',1);
			return;
		}else if(!state.validateEnd){
			Toast.info('通行证有效期不能为空',1);
			return;
		} else if(!state.issueProvinceId){
			Toast.info('签发地点不能为空',1);
			return;
		}

		let postData={
			birthday: state.birthday,
			id: this.id,
			IssueOffice: state.issueOffice,  //省份ID
			IssueProvinceId: state.issueProvinceId, //省份ID
			IssueProvinceName: state.issueProvinceName,
			passCode: state.pass,  //证件号
			passName: state.surname+state.name,
			passNameM: state.surname,
			passNameX: state.name,
			sex: state.sixName,
			validateEnd: state.validateEnd
		}
		setAddPass(postData,(res)=>{
			if(this.type!='disabled'){
				// Toast.info('添加成功',1)
				sessionStorage.setItem('addPass',1)
			}
			window.history.go(-1)
		})
	}

	cancel(){
		alert('', '删除通行证，您将看不到您证件信息，请慎重操作！', [
			{ text: '取消', onPress: () => console.log('cancel') },
			{
				text: '确定',
				onPress: () => {
					//删除订单
					let postData={
						id: this.id
					}
					deletePass(postData,()=>{
						window.history.go(-1)
					})
				},
			},
		])

	}

	onPickerChange = (val) => {
		console.log(val);
	};

    render() {
	    const { getFieldProps } = this.props.form;
	    return (
        <div className={style.addPass}>
	        <div style={{height: '.24rem'}}></div>
	        <div>
		        <Title text='请填写港澳通行证证件信息资料' isLine={true}/>

		        <InputItem  type="text" index='2' itemText="通行证号" maxLength="9" placeHolder="请填写通行证号"
				disabled={this.type == 'disabled'?true:false} id="pass"
				value={this.state.pass} showUnderLine={true} showTagText={true} creditCodeImg={this.state.passImg} creditWidth = {this.state.passWidth}
					onClick={()=>{
						this.setState({
							pass: '',
							passImg: 'hideDelete',
							passNoBlur: false
						})
						document.querySelector('#pass').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({passNoBlur: true});
						setTimeout(()=>{
							if(!this.state.passNoBlur) return;  //点击删除按钮不执行验证
							let value = res;
								{/*passRule = /^0?1[3|4|5|7丨8][0-9]\d{8}$/;*/}
							if(value == ''){
								this.setState({
									passImg: '',
								});
							}else if(value.length>1){
								this.setState({
									passImg: 'correct',
									passWidth: '.4rem'
								});
							}else {
								this.setState({
									passWidth: '.4rem',
									passImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						let value = e.target.value;
						if(value.length!=0&&value==this.state.pass){
							this.setState({
								passImg: 'showDelete',
							});
						}
						setTimeout(()=>{
							document.querySelector('#pass').focus();
						},900)
					}}
					onChange={(e) => {
						console.log('onChange')
						let value = e.target.value;
						let num = ['0','1','2','3','4','5','6','7','8','9'];
						if(value.length==0){
						this.setState({
							pass: value
						})
						} else if(value.length==1){
							if(value.substr(0,1) == 'w'||value.substr(0,1) == 'W'||value.substr(0,1) == 'c'||value.substr(0,1) == 'C'){
								this.setState({
									pass: value.toUpperCase().replace(/(^\s*)|(\s*$)/g, "")
								})
							}
						}else {
							for(let i=0;i<value.length;i++) {
								if(num.indexOf(value[value.length - 1])>-1){
									this.setState({
										pass: value.replace(/(^\s*)|(\s*$)/g, "")
									})
							}
							}
						}

						let pattern = /([^cw]|\s)*/g;  //首字母必须是cw大写
						let patternNum = /([^0-9]|\s)*/g; //document.title
						{/*let regCarNumber = /^[a-zA-Z]+[0-9]{1,}_~!@#$%^&^&$/*/}
						let regCarNumber = /^[w,c]{1}\d{8,10}$/g;
						{/*value.replace(/[^\d]/g,'')"*/}
						{/*let patternNumTo =/[a-zA-z]\d{8,10}$/;*/}
						{/*let reg = /^([a-zA-z]+)(\d{8,10})$/;*/}
						let reg = /^[w,c]+\d{8,10}$/g;
						{/*let text = value.match(reg)*/}
						{/*console.log(text)*/}
						if(value.length>0&&value!=' '){
							this.setState({
								passImg: 'showDelete',
								//pass: e.target.value
							});
						}else {
							this.setState({
								passImg: 'hideDelete',
								// pass: e.target.value
							});
						}
					}}/>

		        <InputItem type="text" index='2' itemText="姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;氏" maxLength="12" placeHolder="请填写姓氏" id="surname"
				disabled={this.type == 'disabled'?true:false} value={this.state.surname} showUnderLine={true} showTagText={true} creditCodeImg={this.state.surnameImg} creditWidth = {this.state.surnameWidth}
					onClick={()=>{
						this.setState({
							surname: '',
							surnameImg: 'hideDelete',
							surnameNoBlur: false
						})
						document.querySelector('#surname').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({surnameNoBlur: true});
						setTimeout(()=>{
							if(!this.state.surnameNoBlur) return;  //点击删除按钮不执行验证
							let value = res;

							if(value == ''){
								this.setState({
									surnameImg: '',
								});
							}else if(checkInformation.name.test(value)){
								this.setState({
									surnameImg: 'correct',
									surnameWidth: '.4rem'
								});
							}else {
								this.setState({
									surnameWidth: '.4rem',
									surnameImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						document.querySelector('#surname').focus();
						setTimeout(()=>{
							document.querySelector('#surname').focus();
						},50)
						let value = e.target.value;
						if(value.length!=0&&value==this.state.surname){
							this.setState({
								surnameImg: 'showDelete',
							});
						}
					}}
					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
						console.log(value.length)
						console.log(value!=' ')
							this.setState({
								surnameImg: 'showDelete',
								surname: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								surnameImg: 'hideDelete',
								surname: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
					}}/>

		        <InputItem type="text" index='2' itemText="名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;字" maxLength="12" placeHolder="请填写名字" id="name"
				disabled={this.type == 'disabled'?true:false} value={this.state.name} showUnderLine={true} showTagText={true} creditCodeImg={this.state.nameImg} creditWidth = {this.state.nameWidth}
					onClick={()=>{
						this.setState({
							name: '',
							nameImg: 'hideDelete',
							nameNoBlur: false
						})
						document.querySelector('#name').focus();
					}}
					onBlur={(event)=>{
						let res = event.target.value;
						this.setState({nameNoBlur: true});
						setTimeout(()=>{
							if(!this.state.nameNoBlur) return;  //点击删除按钮不执行验证
							let value = res;

							if(value == ''){
								this.setState({
									nameImg: '',
								});
							}else if(checkInformation.name.test(value)){
								this.setState({
									nameImg: 'correct',
									nameWidth: '.4rem'
								});
							}else {
								this.setState({
									nameWidth: '.4rem',
									nameImg: 'error'
								})
							}
						},0)
					}}
					onFocus={(e)=>{
						document.querySelector('#name').focus();
						setTimeout(()=>{
							document.querySelector('#name').focus();
						},50)
						let value = e.target.value;
						if(value.length!=0&&value==this.state.name){
							this.setState({
								nameImg: 'showDelete',
							});
						}
					}}
					onChange={(e) => {
						let value = e.target.value;
						if(value.length>0&&value!=' '){
							this.setState({
								nameImg: 'showDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}else {
							this.setState({
								nameImg: 'hideDelete',
								name: e.target.value.replace(/(^\s*)|(\s*$)/g, "")
							});
						}
					}}/>

		        <div className={style.birthDataLine+" birthData"}>
			        <div>
				        <div className="am-list-item am-list-item-middle">
					        <div className="am-list-line" onClick={()=>{this.showListPop()}}>
						        <div className="am-list-content">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</div>
						        <div className="am-list-extra">{this.state.sixName==1?'男':this.state.sixName==2?'女':this.state.sixName}</div>
						        <div className="am-list-arrow am-list-arrow-horizontal">
						        </div>
					        </div>
				        </div>
			        </div>
		        </div>

		        <div className={style.birthDataLine + ' birthData border_top_1'}>
					<DatePicker
						mode="date"
						title="选择日期"
						extra="请选择出生日期"
						className="time_d"
						{...getFieldProps('date1', {

						})}
						minDate={birthMinDate}
						maxDate={birthMaxDate}

						value={this.state.birthData}
						onChange={(v) => {
							this.setState({
								birthData: v,
								visible: false,
								birthday:v.format('YYYY-MM-DD')
							})
							document.querySelectorAll('.am-list-extra')[1].style.color='#6a6a6a';
						}}
					>
						<List.Item arrow="horizontal">出生日期</List.Item>
					</DatePicker>
				</div>

		        <div className={style.birthDataLine +' birthData border_top_1'}>
			        <DatePicker
				        mode="date"
				        title="选择日期"
				        extra="请选择通行证有效期"
				        className="time_d"
				        {...getFieldProps('date1', {

				        })}
				        minDate={passMinDate}
				        maxDate={passMaxDate}

				        value={this.state.passData}
				        onChange={(v) => {
				        	this.setState({
				        		passData: v,
						        visible: false,
						        validateEnd:v.format('YYYY-MM-DD')
					        })
					        document.querySelectorAll('.am-list-extra')[2].style.color='#6a6a6a';
				        }}
			        >
				        <List.Item arrow="horizontal">有效期至</List.Item>
			        </DatePicker>
		        </div>

		        <div className={style.birthDataLine +' birthData border_top_1'}>
			        <Picker data={district} cols={1}
						{...getFieldProps('district3')}
						className="forss"
						value={this.state.asyncValue}
						extra="请选择签发地点"
						onPickerChange={this.onPickerChange}
						onChange={(v) =>{
							this.setState({
							asyncValue: v,
								issueProvinceId: v[0][0], //省份ID
								issueProvinceName: v[0][1], //省
								issueOffice: v[0][0]

							})
							document.querySelectorAll('.am-list-extra')[3].style.color='#6a6a6a';
						}}
			        >
				        <List.Item arrow="horizontal">签发地点</List.Item>
			        </Picker>
		        </div>

	        </div>

	        <div className={style.footBtn}>
				<button type="button" onClick={()=>{this.addPassSubMit()}}>提交保存</button>
		        {
		        	this.type=='disabled'?
					<div className={style.cancel} onClick={()=>{this.cancel()}}>删除</div>:null
		        }
	        </div>
        </div>
      );
    }
}


export default createForm()(AddPass);
